import os
import logging
from flask import Flask, request, jsonify, send_file, render_template
from flask_cors import CORS
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from werkzeug.utils import secure_filename
from model.dgcn_eval import start
from models import db, UserUpload

app = Flask(__name__, static_folder="static", template_folder="templates")
app.config['JWT_SECRET_KEY'] = 'super-secret-key'
jwt = JWTManager(app)
CORS(app)

UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///uploads.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

with app.app_context():
    db.create_all()

ADMIN_PASSWORD = "xutao@1998"

@app.route('/api/upload_file', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({"error": "No file was uploaded"}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No file selected"}), 400

    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(file_path)
        return jsonify({"message": "File uploaded successfully", "file_path": file_path}), 200

    return jsonify({"error": "Invalid file type"}), 400

@app.route('/api/downloadExample', methods=['GET'])
def download_example():
    filename = "sample.csv"
    file_path = os.path.join(os.path.abspath(''), 'model', filename)
    if os.path.exists(file_path):
        return send_file(file_path, as_attachment=True)
    else:
        return jsonify({"error": "File not found"}), 404

@app.route('/api/submit_form', methods=['POST'])
def submit_form():
    data = request.json
    username = data.get('username')
    email = data.get('email')
    file_path = data.get('filePath')

    if not username or not email or not file_path:
        return jsonify({"error": "Missing required form data"}), 400

    new_upload = UserUpload(username=username, email=email, file_path=file_path)
    db.session.add(new_upload)
    db.session.commit()

    log, tableData, log_messages = start(os.path.join(os.path.abspath(''), file_path))

    return jsonify({
        'log': log,
        'tableData': tableData,
        'logMessages': log_messages
    }), 200

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() == 'csv'

@app.route('/api/login', methods=['POST'])
def login():
    data = request.json
    if data['password'] == ADMIN_PASSWORD:
        access_token = create_access_token(identity={'role': 'admin'})
        return jsonify(access_token=access_token), 200
    else:
        return jsonify({"authenticated": False, "message": "Incorrect password"}), 401

@app.route('/api/users', methods=['GET'])
@jwt_required()
def get_users():
    user_uploads = UserUpload.query.all()
    users = [
        {"username": user.username, "email": user.email, "file": user.file_path}
        for user in user_uploads
    ]
    return jsonify(users), 200

@app.route('/api/download/<filename>', methods=['GET'])
@jwt_required()
def download_file(filename):
    filename = secure_filename(filename)
    file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    if os.path.exists(file_path):
        return send_file(file_path, as_attachment=True)
    else:
        return jsonify({"error": "File not found"}), 404

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
